package servlet;

import bean.DealRecord;
import bean.User;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import dao.DealRecordDao;
import dao.UserDao;
import net.sf.json.JSONObject;
import util.AlipayConfig;
import util.DateUtil;
import util.DealRecordUtil;
import util.JsonWrapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用于接收支付宝同步通知并验签，交易记录数据入库（update（更改alipayStatus值））
 *
 * @author dsf
 */
@WebServlet(name = "AlipayReturnServlet", urlPatterns = "/rechargeReturn")
public class AlipayReturnServlet extends HttpServlet {

    private static String baseUrl = "http://115.159.92.47/user/#/rechargeReturn?";
//    private static String baseUrl = " http://2mwtcv.natappfree.cc/user/#/rechargeReturn?";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JsonWrapper result = new JsonWrapper();
        JSONObject returnObject = new JSONObject();
        //http状态码
        //获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = req.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                    : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            //验签成功
            if (signVerified) {
                //商户订单号
                String out_trade_no = new String(req.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                //付款金额
                String total_amount = new String(req.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
                DealRecordDao drDao = new DealRecordDao();
                UserDao userDao = new UserDao();
                // 付款成功后执行以下业务
                DealRecord drSearchPara = new DealRecord();
                drSearchPara.setDealRecordId(out_trade_no);
                List<Object> drSearchRes;
                // 从数据库查找id对应的交易记录
                try {
                    drSearchRes = drDao.dealrecordSearch(null, drSearchPara, null);
                    if (drSearchRes.size() != 0) {
                        DealRecord drSearchObject = (DealRecord) drSearchRes.get(0);
                        //该订单处于为确认支付状态
                        if ("1".equals(drSearchObject.getAlipayStatus())) {
                            //设置修改user表信息的参数
                            User userModifyPara = new User();
                            userModifyPara.setUserId(drSearchObject.getUserId());
                            userModifyPara.setBalance(drSearchObject.getCurBalance());
                            //设置修改dealrecord表信息的参数
                            DealRecord drModifyPara = new DealRecord();
                            drModifyPara.setDealRecordId(out_trade_no);
                            // 修改alipayStatus值为2
                            drModifyPara.setAlipayStatus("2");
                            //执行修改dealrecord表操作
                            int drModifyRes = drDao.dealrecordModify(drModifyPara);
                            if (drModifyRes != 0) {
                                //dealrecord表修改成功，证明充值成功完成且入库成功，修改user表的用户余额
                                int userModifyRes = userDao.userModify(userModifyPara);
                                if (userModifyRes != 0) {
                                    User userSearchPara = new User();
                                    userSearchPara.setUserId(drSearchObject.getUserId());
                                    List<Object> userSearchRes;
                                    userSearchRes = userDao.userList(null, userSearchPara);
                                    User userSearchObject = (User) userSearchRes.get(0);
                                    String balance = DealRecordUtil.formatBalance(userSearchObject.getBalance());
                                    String money = drSearchObject.getMoney();
                                    //查询成功向前端返回对应数据
                                    //                  returnObject.put("userName", userSearchObject.getUserName());
//                  returnObject.put("time", drSearchObject.getActionTime());
//                  returnObject.put("money", drSearchObject.getMoney());
//                  returnObject.put("balance", DealRecordUtil.formatBalance(userSearchObject.getBalance()));
//                  result.setDataEntry("return", returnObject);
                                    System.out.println(drSearchObject);
                                    resp.sendRedirect(baseUrl + "c=1&m=" + money + "&b=" + balance + "&un=" + userSearchObject.getUserName() + "&time=" + drSearchObject.getActionTime());
                                    return;
                                } else {
                                    System.out.println("modify user table failed!");
                                }
                            }
                            //支付状态已确认为成功
                        } else {
                            User userSearchPara = new User();
                            userSearchPara.setUserId(drSearchObject.getUserId());
                            List<Object> userSearchRes;
                            userSearchRes = userDao.userList(null, userSearchPara);
                            User userSearchObject = (User) userSearchRes.get(0);
                            //查询成功向前端返回对应数据
//              status = 200;
//              msg = "success";
                            String balance = DealRecordUtil.formatBalance(userSearchObject.getBalance());
                            String money = drSearchObject.getMoney();
                            System.out.println(drSearchObject);
                            resp.sendRedirect(baseUrl + "c=1&m=" + money + "&b=" + balance + "&un=" + userSearchObject.getUserName() + "&time=" + drSearchObject.getActionTime());
                            return;
                        }
                    } else {
                        System.out.println("No drId is same to what from alipay!");
                        resp.sendRedirect(baseUrl + "c=403&time=" + DateUtil.nowSymbolTime());
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    resp.sendRedirect(baseUrl + "c=403&time=" + DateUtil.nowSymbolTime());
                    return;
                }
            } else {
                System.out.println("sign vertify failed!");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            resp.sendRedirect(baseUrl + "c=403&time=" + DateUtil.nowSymbolTime());
            return;
        }
        resp.sendRedirect(baseUrl + "c=403&time=" + DateUtil.nowSymbolTime());
    }
}